<script setup>
import { ref, computed, onMounted, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
import { useInventoryStore } from '../../stores/inventory'
import { useItemsStore } from '../../stores/items'
import { ElMessage, ElMessageBox } from 'element-plus'
import { messageHelper } from '../../utils/messageHelper'
import { 
  Warning, Check, Delete, Clock, Plus, Minus, More, Edit,
  OfficeBuilding, ShoppingBag, Food, Cpu, Select
} from '@element-plus/icons-vue'
import ItemDetailModal from '../../components/items/ItemDetailModal.vue' // 导入物品详情模态框组件

const router = useRouter()
const inventoryStore = useInventoryStore()
const itemsStore = useItemsStore()

// 修改：将默认标签页改为"全部物品"
const activeTab = ref('allInventory')
const loading = ref(true)

// 物品详情模态框相关状态
const detailModalVisible = ref(false)
const itemToEdit = ref(null)

// 选中的物品
const selectedItems = ref({
  lowStock: [],
  expiring: [],
  expired: [],
  allInventory: [],
  sufficient: []
})

// 模拟数据
const mockData = {
  // 低库存物品
  lowStock: [
    {
      id: 'ls1',
      name: '洗手液',
      category: '日用品',
      location: '卫生间',
      quantity: 1,
      purchaseDate: '2023-09-15',
      notes: '需要补充'
    },
    {
      id: 'ls2',
      name: '纸巾',
      category: '日用品',
      location: '客厅',
      quantity: 2,
      purchaseDate: '2023-10-20'
    },
    {
      id: 'ls3',
      name: '牙膏',
      category: '日用品',
      location: '卫生间',
      quantity: 1,
      purchaseDate: '2023-11-05'
    },
    {
      id: 'ls4',
      name: '洗发水',
      category: '日用品',
      location: '卫生间',
      quantity: 1,
      purchaseDate: '2023-10-10'
    }
  ],
  
  // 即将过期物品
  expiring: [
    {
      id: 'ex1',
      name: '鸡蛋',
      category: '食品',
      location: '冰箱',
      quantity: 6,
      purchaseDate: '2023-11-25',
      expiryDate: '2023-12-15',
      notes: '早餐食材'
    },
    {
      id: 'ex2',
      name: '牛奶',
      category: '食品',
      location: '冰箱',
      quantity: 2,
      purchaseDate: '2023-11-20',
      expiryDate: '2023-12-10'
    },
    {
      id: 'ex3',
      name: '酸奶',
      category: '食品',
      location: '冰箱',
      quantity: 3,
      purchaseDate: '2023-11-28',
      expiryDate: '2023-12-12'
    },
    {
      id: 'ex4',
      name: '猪肉',
      category: '食品',
      location: '冰箱',
      quantity: 1,
      purchaseDate: '2023-11-27',
      expiryDate: '2023-12-05'
    }
  ],
  
  // 已过期物品
  expired: [
    {
      id: 'xp1',
      name: '酱油',
      category: '食品',
      location: '厨房',
      quantity: 1,
      purchaseDate: '2023-05-15',
      expiryDate: '2023-11-20'
    },
    {
      id: 'xp2',
      name: '维他命C',
      category: '药品',
      location: '卧室',
      quantity: 1,
      purchaseDate: '2022-10-10',
      expiryDate: '2023-10-10'
    },
    {
      id: 'xp3',
      name: '芝麻酱',
      category: '食品',
      location: '厨房',
      quantity: 1,
      purchaseDate: '2023-01-15',
      expiryDate: '2023-11-15'
    }
  ]
}

// 获取所有物品，从 itemsStore
const allItems = computed(() => {
  if (Array.isArray(itemsStore.items)) {
    console.log(`库存管理：获取到${itemsStore.items.length}个物品`);
    return itemsStore.items;
  }
  return [];
})

// 添加计算属性：仅获取消耗品
const consumableItems = computed(() => {
  return allItems.value.filter(item => item.isConsumable === 1);
})

// 低库存物品：数量少于或等于阈值的物品
const lowStockItems = computed(() => {
  const lowStockThreshold = 3; // 库存阈值，可以根据需要调整
  return consumableItems.value.filter(item => {
    // 确保数量字段存在且为数字
    const quantity = parseInt(item.quantity || 0);
    return quantity <= lowStockThreshold && quantity > 0;
  });
})

// 即将过期物品：到期日在30天内
const expiringItems = computed(() => {
  const daysThreshold = 30; // 30天内到期视为即将过期
  return consumableItems.value.filter(item => {
    if (!item.expiryDate) return false;
    const daysRemaining = calculateDaysRemaining(item.expiryDate);
    return daysRemaining !== null && daysRemaining > 0 && daysRemaining <= daysThreshold;
  });
})

// 已过期物品：当前日期已超过到期日
const expiredItems = computed(() => {
  return consumableItems.value.filter(item => {
    if (!item.expiryDate) return false;
    const daysRemaining = calculateDaysRemaining(item.expiryDate);
    return daysRemaining !== null && daysRemaining <= 0;
  });
})

// 状态良好物品：数量充足且不即将过期的物品
const sufficientStockItems = computed(() => {
  const stockThreshold = 3; // 库存阈值，超过此值视为充足
  const expiryThreshold = 30; // 过期阈值，超过此天数视为安全期
  
  return consumableItems.value.filter(item => {
    // 确保数量字段存在且为数字
    const quantity = parseInt(item.quantity || 0);
    
    // 检查过期日期
    let notExpiringSoon = true;
    if (item.expiryDate) {
      const daysRemaining = calculateDaysRemaining(item.expiryDate);
      // 如果天数为null或小于等于30天，则视为即将过期
      notExpiringSoon = daysRemaining === null || daysRemaining > expiryThreshold;
    }
    
    // 同时满足数量充足和不即将过期
    return quantity > stockThreshold && notExpiringSoon;
  });
})

// 过滤后的物品 - 这里我们直接使用上面的计算属性，不需要额外过滤
const filteredLowStockItems = computed(() => lowStockItems.value)
const filteredExpiringItems = computed(() => expiringItems.value)
const filteredExpiredItems = computed(() => expiredItems.value)

// 获取物品数据
const fetchItems = async () => {
  loading.value = true
  try {
    // 修改：使用 fetchAllItems 获取所有物品
    const locationId = localStorage.getItem('currentLocationId') || null;
    console.log('获取库存管理数据，使用locationId:', locationId);
    
    await itemsStore.fetchAllItems(locationId);
    console.log(`库存管理：成功获取到${itemsStore.items.length}个物品`);
    
    // 如果是使用模拟数据，确保库存页面的模拟数据也已加载
    if (itemsStore.dataSource === 'mock') {
      // 保持模拟数据延迟效果
      setTimeout(() => {
        loading.value = false
      }, 400)
    } else {
      loading.value = false
    }
  } catch (error) {
    console.error('获取库存物品数据失败:', error);
    console.error('错误堆栈:', error.stack);
    
    // 确保使用模拟数据作为后备
    if (typeof itemsStore.initMockData === 'function') {
      itemsStore.initMockData()
      ElMessage.warning('无法连接到后端服务，当前使用本地模拟数据')
    }
    loading.value = false
  }
}

// 处理物品详情保存
const handleDetailSave = async (updatedItem) => {
  try {
    // 对于库存管理中的模拟数据，需要根据ID类型来处理
    if (updatedItem.id && typeof updatedItem.id === 'string' && 
        (updatedItem.id.startsWith('ls') || updatedItem.id.startsWith('ex') || updatedItem.id.startsWith('xp'))) {
      // 模拟数据更新
      if (updatedItem.id.startsWith('ls')) {
        const index = mockData.lowStock.findIndex(i => i.id === updatedItem.id)
        if (index !== -1) {
          mockData.lowStock[index] = {...mockData.lowStock[index], ...updatedItem}
        }
      } else if (updatedItem.id.startsWith('ex')) {
        const index = mockData.expiring.findIndex(i => i.id === updatedItem.id)
        if (index !== -1) {
          mockData.expiring[index] = {...mockData.expiring[index], ...updatedItem}
        }
      } else if (updatedItem.id.startsWith('xp')) {
        const index = mockData.expired.findIndex(i => i.id === updatedItem.id)
        if (index !== -1) {
          mockData.expired[index] = {...mockData.expired[index], ...updatedItem}
        }
      }
    }
    
    // 同时更新itemsStore中的数据
    await itemsStore.updateItem(updatedItem.id, updatedItem)
    
    ElMessage({
      message: '更新成功',
      type: 'success',
      duration: 2000
    })
    
    // 关闭模态框
    detailModalVisible.value = false
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  }
}

// 辅助方法：将模拟数据中的类别名称转换为ID
const getCategoryIdByName = (categoryName) => {
  const category = itemsStore.categories.find(c => c.name === categoryName)
  return category ? category.id : null
}

// 辅助方法：将模拟数据中的位置名称转换为ID
const getLocationIdByName = (locationName) => {
  const location = itemsStore.locations.find(l => l.name === locationName)
  return location ? location.id : null
}

// 打开物品详情
const showItemDetails = (item) => {
  // 创建深拷贝防止直接修改
  const clonedItem = JSON.parse(JSON.stringify(item))
  
  // 确保模拟数据有正确的类别和位置ID
  if (typeof clonedItem.id === 'string' && 
      (clonedItem.id.startsWith('ls') || clonedItem.id.startsWith('ex') || clonedItem.id.startsWith('xp'))) {
    // 如果模拟数据中使用的是名称而不是ID，尝试转换为ID
    if (clonedItem.category && !clonedItem.categoryId) {
      clonedItem.categoryId = getCategoryIdByName(clonedItem.category)
    }
    if (clonedItem.location && !clonedItem.locationId) {
      clonedItem.locationId = getLocationIdByName(clonedItem.location)
    }
  }
  
  itemToEdit.value = clonedItem
  detailModalVisible.value = true
}

// 更新物品数量
const updateQuantity = async (item, quantity) => {
  try {
    // 先更新本地模拟数据
    const targetItem = mockData.lowStock.find(i => i.id === item.id)
    if (targetItem) {
      targetItem.quantity = quantity
    }
    
    // 同时更新itemsStore中的数据
    await itemsStore.updateItem(item.id, { quantity })
    
    // 重新加载物品数据以刷新UI
    await fetchItems()
    
    ElMessage({
      message: '数量更新成功',
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  }
}

// 删除过期物品
const removeExpiredItem = async (item) => {
  try {
    await ElMessageBox.confirm(`确定要删除过期物品 "${item.name}" 吗？`, '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟删除操作
    const index = mockData.expired.findIndex(i => i.id === item.id)
    if (index !== -1) {
      mockData.expired.splice(index, 1)
    }
    // 正式环境应使用:
    // await itemsStore.deleteItem(item.id)
    ElMessage.success('物品已删除')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const calculateDaysRemaining = (dateString) => {
  if (!dateString) return null
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  const expiryDate = new Date(dateString)
  expiryDate.setHours(0, 0, 0, 0)
  
  const diffTime = expiryDate - today
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays
}

// 获取各类物品的数量统计
const summaryStats = computed(() => [
  { 
    id: 'lowStock',
    label: '低库存物品',
    count: lowStockItems.value.length,
    icon: Warning,
    color: 'orange'
  },
  { 
    id: 'sufficient',
    label: '状态良好',
    count: sufficientStockItems.value.length,
    icon: Check,
    color: 'green'
  },
  { 
    id: 'expiring',
    label: '即将过期物品',
    count: expiringItems.value.length,
    icon: Clock,
    color: 'orange'
  },
  { 
    id: 'expired',
    label: '已过期物品',
    count: expiredItems.value.length,
    icon: Delete,
    color: 'red'
  },
  { 
    id: 'allInventory',
    label: '全部物品',
    count: consumableItems.value.length,
    icon: Select,
    color: 'blue'
  }
])

// 获取物品分类图标
const getCategoryIcon = (category) => {
  switch (category) {
    case '电子产品': return Cpu
    case '家具': return OfficeBuilding
    case '食品': return Food
    case '衣物': return ShoppingBag
    default: return More
  }
}

// 获取物品类别颜色
const getCategoryColor = (category) => {
  switch (category) {
    case '电子产品': return 'blue'
    case '家具': return 'brown'
    case '食品': return 'green'
    case '衣物': return 'purple'
    case '日用品': return 'teal'
    case '药品': return 'pink'
    default: return 'gray'
  }
}

// 添加加载动画效果
watchEffect(() => {
  if (loading.value) {
    document.body.style.cursor = 'progress'
  } else {
    document.body.style.cursor = 'default'
  }
})

// 标记物品为已使用
const markAsUsed = async (item) => {
  try {
    await ElMessageBox.confirm(`确定将 "${item.name}" 标记为已使用吗？`, '确认标记', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    // 模拟操作
    const index = mockData.expiring.findIndex(i => i.id === item.id)
    if (index !== -1) {
      mockData.expiring.splice(index, 1)
    }
    
    // 正式环境应使用:
    // await inventoryStore.markItemAsUsed(item.id)
    ElMessage.success('物品已标记为已使用')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + error.message)
    }
  }
}

// 物品选择相关方法
const isSelected = (item, category) => {
  return selectedItems.value[category].includes(item.id)
}

const toggleSelect = (item, category) => {
  const index = selectedItems.value[category].indexOf(item.id)
  if (index === -1) {
    selectedItems.value[category].push(item.id)
  } else {
    selectedItems.value[category].splice(index, 1)
  }
}

const toggleSelectAll = (category, items) => {
  if (selectedItems.value[category].length === items.length) {
    // 如果全部选中，则清空选择
    selectedItems.value[category] = []
  } else {
    // 否则全选
    selectedItems.value[category] = items.map(item => item.id)
  }
}

// 批量更新物品数量
const batchUpdateQuantity = async () => {
  try {
    const { value } = await ElMessageBox.prompt('请输入要增加的数量', '批量增加数量', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^\d+$/,
      inputErrorMessage: '请输入有效的数字'
    })
    
    const increment = parseInt(value)
    
    if (isNaN(increment) || increment <= 0) {
      ElMessage.warning('请输入大于0的有效数字')
      return
    }
    
    // 显示加载状态
    loading.value = true
    
    // 确定当前操作的是哪个标签页
    const currentTab = activeTab.value
    const selectedIds = selectedItems.value[currentTab] || []
    
    if (selectedIds.length === 0) {
      ElMessage.warning('请先选择要操作的物品')
      loading.value = false
      return
    }
    
    // 遍历选中的物品，更新数量
    for (const itemId of selectedIds) {
      try {
        // 根据当前标签页获取正确的物品列表
        let targetItem
        let targetItemList = []
        
        if (currentTab === 'lowStock') {
          targetItemList = mockData.lowStock
        } else if (currentTab === 'allInventory') {
          targetItemList = consumableItems.value
        }
        
        // 从物品列表中找到对应的物品
        targetItem = targetItemList.find(item => item.id === itemId)
        
        if (targetItem) {
          const newQuantity = targetItem.quantity + increment
          
          // 更新本地数据
          if (typeof targetItem.id === 'string') {
            // 处理模拟数据
            if (targetItem.id.startsWith('ls')) {
              const mockItem = mockData.lowStock.find(i => i.id === targetItem.id)
              if (mockItem) {
                mockItem.quantity = newQuantity
              }
            } else if (targetItem.id.startsWith('ex')) {
              const mockItem = mockData.expiring.find(i => i.id === targetItem.id)
              if (mockItem) {
                mockItem.quantity = newQuantity
              }
            } else if (targetItem.id.startsWith('xp')) {
              const mockItem = mockData.expired.find(i => i.id === targetItem.id)
              if (mockItem) {
                mockItem.quantity = newQuantity
              }
            }
          }
          
          // 调用API更新
          await itemsStore.updateItem(targetItem.id, { quantity: newQuantity })
        } else {
          console.error(`未找到ID为 ${itemId} 的物品`)
        }
      } catch (error) {
        console.error(`更新物品 ${itemId} 数量失败:`, error)
        }
      }
    
    // 发送库存更新通知
    if (selectedIds.length > 0) {
      // 尝试获取第一个物品的位置信息
      let locationName = '未知位置'
      let locationId = null
      
      // 根据当前标签页获取正确的物品列表
      let itemList = []
      if (currentTab === 'lowStock') {
        itemList = mockData.lowStock
      } else if (currentTab === 'allInventory') {
        itemList = consumableItems.value
      }
      
      const firstItem = itemList.find(item => item.id === selectedIds[0])
      if (firstItem) {
        locationName = firstItem.locationName || firstItem.specificLocation || firstItem.location || '未知位置'
        locationId = firstItem.locationId || getLocationIdByName(locationName)
      }
      
      await messageHelper.createNotification({
        title: '批量库存更新',
        content: `已为${selectedIds.length}个物品增加了${increment}个数量`,
        type: 'inventory',
        locationId: locationId
      })
    }
    
    loading.value = false
    ElMessage.success(`已成功为${selectedIds.length}个物品增加${increment}个数量`)
    
    // 重新加载物品数据以刷新UI
    await fetchItems()
    
    // 清空选择
    selectedItems.value[currentTab] = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量操作失败: ' + (error.message || '未知错误'))
    }
    loading.value = false
  }
}

// 批量标记为已使用
const batchMarkAsUsed = async () => {
  try {
    await ElMessageBox.confirm(`确定要将所有选中的即将过期物品（${selectedItems.value.expiring.length}个）标记为已使用吗？`, '批量操作', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })
    
    // 模拟批量标记
    for (const itemId of selectedItems.value.expiring) {
      const index = mockData.expiring.findIndex(i => i.id === itemId)
      if (index !== -1) {
        mockData.expiring.splice(index, 1)
      }
    }
    
    // 正式环境应使用:
    // await Promise.all(selectedItems.value.expiring.map(id => inventoryStore.markItemAsUsed(id)))
    ElMessage.success(`已成功标记 ${selectedItems.value.expiring.length} 个物品为已使用`)
    selectedItems.value.expiring = [] // 清空选择
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量标记失败: ' + error.message)
    }
  }
}

// 批量删除过期物品
const batchRemoveExpiredItems = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除所有选中的过期物品（${selectedItems.value.expired.length}个）吗？`, '批量操作', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟批量删除
    for (const itemId of selectedItems.value.expired) {
      const index = mockData.expired.findIndex(i => i.id === itemId)
      if (index !== -1) {
        mockData.expired.splice(index, 1)
      }
    }
    
    // 正式环境应使用:
    // await Promise.all(selectedItems.value.expired.map(id => itemsStore.deleteItem(id)))
    ElMessage.success(`已成功删除 ${selectedItems.value.expired.length} 个过期物品`)
    selectedItems.value.expired = [] // 清空选择
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + error.message)
    }
  }
}

// 添加获取状态标签类型的函数
const getStatusTagType = (status) => {
  switch (status) {
    case '正常使用': return 'success';
    case '闲置': return 'info';
    case '已损坏': return 'danger';
    case '借出': return 'warning';
    case '需要替换': return 'warning';
    case '已过期': return 'danger';
    default: return 'info';
  }
}

// 通用选择处理函数
const handleSelectionChange = (tabName, selection) => {
  selectedItems.value[tabName] = selection
}

// 新增：获取当前激活标签页的物品列表
const currentItemList = computed(() => {
    switch (activeTab.value) {
        case 'lowStock': return filteredLowStockItems.value;
        case 'expiring': return filteredExpiringItems.value;
        case 'expired': return filteredExpiredItems.value;
        case 'allInventory': return consumableItems.value;
        case 'sufficient': return sufficientStockItems.value;
        default: return [];
    }
})

// 新增：获取当前激活标签页选中的物品列表
const currentSelectedItems = computed(() => selectedItems.value[activeTab.value] || []);

// 减少物品数量
const decreaseQuantity = async (item) => {
  // 如果数量已经是1，不能再减少
  if (item.quantity <= 1) {
    ElMessage({
      message: '数量已经是最小值，不能再减少',
      type: 'warning',
      duration: 2000
    })
    return
  }
  
  try {
    const newQuantity = item.quantity - 1
    
    // 先更新本地模拟数据
    if (typeof item.id === 'string') {
      if (item.id.startsWith('ls')) {
        const targetItem = mockData.lowStock.find(i => i.id === item.id)
        if (targetItem) {
          targetItem.quantity = newQuantity
        }
      } else if (item.id.startsWith('ex')) {
        const targetItem = mockData.expiring.find(i => i.id === item.id)
        if (targetItem) {
          targetItem.quantity = newQuantity
        }
      } else if (item.id.startsWith('xp')) {
        const targetItem = mockData.expired.find(i => i.id === item.id)
        if (targetItem) {
          targetItem.quantity = newQuantity
        }
      }
    }
    
    // 同时更新itemsStore中的数据
    await itemsStore.updateItem(item.id, { quantity: newQuantity })
    
    // 重新加载物品数据以刷新UI
    await fetchItems()
    
    ElMessage({
      message: '数量减少成功',
      type: 'success',
      duration: 2000
    })
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.message || '未知错误'))
  }
}

// 刷新物品数据
const refreshItemData = async () => {
  if (itemToEdit.value && itemToEdit.value.id) {
    // 从store获取最新数据
    const updatedItem = await itemsStore.getItemById(itemToEdit.value.id)
    if (updatedItem) {
      // 更新本地数据
      itemToEdit.value = {...updatedItem}
      
      // 更新模拟数据
      if (typeof updatedItem.id === 'string') {
        if (updatedItem.id.startsWith('ls')) {
          const index = mockData.lowStock.findIndex(i => i.id === updatedItem.id)
          if (index !== -1) {
            mockData.lowStock[index] = {...updatedItem}
          }
        } else if (updatedItem.id.startsWith('ex')) {
          const index = mockData.expiring.findIndex(i => i.id === updatedItem.id)
          if (index !== -1) {
            mockData.expiring[index] = {...updatedItem}
          }
        } else if (updatedItem.id.startsWith('xp')) {
          const index = mockData.expired.findIndex(i => i.id === updatedItem.id)
          if (index !== -1) {
            mockData.expired[index] = {...updatedItem}
          }
        }
      }
    }
  }
}

// 在组件挂载时加载数据
onMounted(async () => {
  await fetchItems();
  console.log('库存管理组件已加载');
})

// 监听路由变化，确保路由参数变化时重新加载数据
watchEffect(async () => {
  const locationId = localStorage.getItem('currentLocationId');
  if (locationId) {
    console.log('检测到位置ID变化，重新加载库存数据:', locationId);
    await fetchItems();
  }
})

// 获取分类名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return '-'
  const category = itemsStore.categories.find(c => c.id === categoryId)
  return category ? category.name : '-'
}

// 库存盘点功能
const performInventoryCheck = async (locationId, locationName) => {
  try {
    const { value: confirm } = await ElMessageBox.confirm(
      '确定要对当前库存进行盘点吗？这将生成一份库存报告并发送通知。',
      '库存盘点确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 显示加载状态
    loading.value = true
    
    // 根据活动标签页选择要盘点的物品列表
    let itemsToCheck = []
    if (activeTab.value === 'allInventory') {
      itemsToCheck = allItems.value
    } else if (activeTab.value === 'lowStock') {
      itemsToCheck = filteredLowStockItems.value
    } else if (activeTab.value === 'expiring') {
      itemsToCheck = filteredExpiringItems.value
    } else if (activeTab.value === 'expired') {
      itemsToCheck = filteredExpiredItems.value
    }
    
    // 获取相关统计数据
    const totalItems = itemsToCheck.length
    const lowStockItems = itemsToCheck.filter(item => item.quantity <= 3).length
    const expiringItems = itemsToCheck.filter(item => item.expiryDate && 
      new Date(item.expiryDate) > new Date() && 
      new Date(item.expiryDate) < new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)).length
    const expiredItems = itemsToCheck.filter(item => item.expiryDate && 
      new Date(item.expiryDate) < new Date()).length
    
    // 创建库存盘点通知
    await messageHelper.createInventoryCheckNotification(
      locationName || '全部位置',
      locationId || 0,
      totalItems
    )
    
    // 创建详细的库存盘点活动记录
    await messageHelper.recordActivity({
      title: '库存盘点',
      content: `完成库存盘点：共有${totalItems}件物品，其中库存不足${lowStockItems}件，即将过期${expiringItems}件，已过期${expiredItems}件。`,
      actionType: 'update',
      locationName: locationName || '全部位置',
      locationId: locationId || 0
    })
    
    loading.value = false
    ElMessage.success('库存盘点完成')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('库存盘点失败: ' + (error.message || '未知错误'))
    }
    loading.value = false
  }
}

// 数量充足物品
const filteredSufficientItems = computed(() => sufficientStockItems.value)
</script>

<template>
  <div class="inventory-view">
    <!-- 头部区域 -->
    <div class="inventory-header">
      <h1 class="page-title">库存管理</h1>

      <!-- 将全选按钮移到这里 -->
      <div class="header-actions">
        <el-button 
          v-if="currentItemList.length > 0" 
          type="primary" 
          plain
          size="small" 
          @click="toggleSelectAll(activeTab, currentItemList)"
          class="select-all-header-btn"
        >
          {{ currentSelectedItems.length === currentItemList.length ? '取消全选' : '全选当页' }}
        </el-button>
        
        <!-- 添加库存盘点按钮 -->
        <el-button
          type="success"
          plain
          size="small"
          @click="performInventoryCheck(null, null)"
          class="inventory-check-btn"
        >
          <el-icon><Check /></el-icon>
          库存盘点
        </el-button>
      </div>
      
      <!-- 显示选择的物品数量和批量操作按钮 -->
      <div v-if="currentSelectedItems.length > 0" class="selection-actions">
        <div class="selected-count">已选择 {{ currentSelectedItems.length }} 个物品</div>
        
        <div class="batch-actions">
          <!-- 低库存标签页的批量操作按钮 -->
          <template v-if="activeTab === 'lowStock'">
        <el-button type="primary" size="small" @click="batchUpdateQuantity">
          批量增加数量
        </el-button>
          </template>
    
          <!-- 即将过期标签页的批量操作按钮 -->
          <template v-else-if="activeTab === 'expiring'">
            <el-button type="primary" size="small" @click="batchMarkAsUsed">
              批量标记为已使用
        </el-button>
          </template>
      
          <!-- 已过期标签页的批量操作按钮 -->
          <template v-else-if="activeTab === 'expired'">
        <el-button type="danger" size="small" @click="batchRemoveExpiredItems">
          批量删除
        </el-button>
          </template>
          
          <!-- 全部物品标签页的批量操作按钮 -->
          <template v-else-if="activeTab === 'allInventory'">
            <el-button type="primary" size="small" @click="batchUpdateQuantity">
              批量增加数量
            </el-button>
          </template>
        </div>
      </div>
    </div>
      
    <!-- 标签页导航 -->
    <div class="inventory-tabs">
      <div 
        class="tab" 
        :class="{'active': activeTab === 'allInventory'}" 
          @click="activeTab = 'allInventory'"
        >
        <span>全部物品</span>
      </div>
      <div 
        class="tab" 
        :class="{'active': activeTab === 'sufficient'}" 
          @click="activeTab = 'sufficient'"
        >
        <span>状态良好</span>
      </div>
      <div 
        class="tab" 
        :class="{'active': activeTab === 'lowStock'}" 
          @click="activeTab = 'lowStock'"
        >
        <span>低库存(<=3)</span>
      </div>
      <div 
        class="tab" 
        :class="{'active': activeTab === 'expiring'}" 
          @click="activeTab = 'expiring'"
        >
        <span>即将过期(7天内)</span>
      </div>
      <div 
        class="tab" 
        :class="{'active': activeTab === 'expired'}" 
          @click="activeTab = 'expired'"
        >
        <span>已过期</span>
      </div>
    </div>
    
    <div class="inventory-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载库存数据中...</p>
      </div>
      
      <!-- 低库存物品 -->
      <div v-if="activeTab === 'lowStock'" class="inventory-list">
          <div v-if="filteredLowStockItems.length === 0" class="empty-state">
          <div class="empty-icon">📊</div>
          <h3>没有低库存物品</h3>
          <p>当前没有数量少于3的消耗品</p>
          </div>
        <div v-else>
          <div class="item-cards">
            <div 
              v-for="item in filteredLowStockItems" 
              :key="item.id"
              class="item-card low-stock"
              :class="{ 'selected': isSelected(item, 'lowStock') }"
              @click="showItemDetails(item)"
            >
              <!-- 选择框 -->
              <div class="select-box" @click.stop="toggleSelect(item, 'lowStock')">
                <el-icon v-if="isSelected(item, 'lowStock')"><Check /></el-icon>
              </div>
              
              <div class="card-header">
                <div class="card-title">
                  {{ item.name }}
                  <span class="warning-tag" v-if="item.quantity <= 3 && !(item.expiryDate && calculateDaysRemaining(item.expiryDate) <= 0)">低库存</span>
                </div>
                <div class="card-quantity">
                <span class="quantity-label">数量:</span>
                  <span class="quantity-value low">{{ item.quantity }}</span>
                </div>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ item.location }}</span>
            </div>
                <div class="info-item">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>{{ getCategoryName(item.categoryId) }}</span>
          </div>
        </div>
              <div class="card-footer">
                <div class="card-date">购买于: {{ item.purchaseDate }}</div>
                <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
              </div>
              
              <!-- 添加操作按钮组 -->
              <div class="card-actions">
                <el-button type="primary" size="small" circle @click.stop="updateQuantity(item, item.quantity + 1)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button type="warning" size="small" circle @click.stop="decreaseQuantity(item)">
                  <el-icon><Minus /></el-icon>
                </el-button>
              </div>
                </div>
          </div>
                </div>
              </div>
              
      <!-- 即将过期物品 -->
      <div v-else-if="activeTab === 'expiring'" class="inventory-list">
        <div v-if="filteredExpiringItems.length === 0" class="empty-state">
          <div class="empty-icon">🕒</div>
          <h3>没有即将过期物品</h3>
          <p>当前没有即将过期的物品</p>
                </div>
        <div v-else>
          <div class="item-cards">
            <div 
              v-for="item in filteredExpiringItems" 
              :key="item.id"
              class="item-card expiring"
              :class="{ 'selected': isSelected(item, 'expiring') }"
              @click="showItemDetails(item)"
            >
              <!-- 选择框 -->
              <div class="select-box" @click.stop="toggleSelect(item, 'expiring')">
                <el-icon v-if="isSelected(item, 'expiring')"><Check /></el-icon>
                  </div>
              
              <div class="card-header">
                <div class="card-title">
                  {{ item.name }}
                  <span class="expiring-tag" v-if="item.expiryDate && calculateDaysRemaining(item.expiryDate) > 0 && calculateDaysRemaining(item.expiryDate) <= 30">即将过期</span>
                </div>
                <div class="card-quantity">
                  <span class="quantity-label">数量:</span>
                  <span class="quantity-value" :class="{'low': item.quantity <= 3}">{{ item.quantity }}</span>
                </div>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ item.location }}</span>
            </div>
                <div class="info-item">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>{{ getCategoryName(item.categoryId) }}</span>
                </div>
              </div>
              <div class="card-footer">
                <div class="card-date warning">过期日期: {{ item.expiryDate }}</div>
                <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
              </div>
              
              <!-- 添加操作按钮组 -->
              <div class="card-actions">
                <el-button type="success" size="small" circle @click.stop="markAsUsed(item)">
                  <el-icon><Check /></el-icon>
                </el-button>
                <el-button type="warning" size="small" circle @click.stop="decreaseQuantity(item)">
                  <el-icon><Minus /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
          </div>
        </div>
        
        <!-- 已过期物品 -->
      <div v-else-if="activeTab === 'expired'" class="inventory-list">
          <div v-if="filteredExpiredItems.length === 0" class="empty-state">
          <div class="empty-icon">✓</div>
          <h3>没有已过期物品</h3>
          <p>太好了，没有过期物品需要处理</p>
          </div>
        <div v-else>
          <div class="item-cards">
            <div 
              v-for="item in filteredExpiredItems" 
              :key="item.id"
              class="item-card expired"
              :class="{ 'selected': isSelected(item, 'expired') }"
              @click="showItemDetails(item)"
            >
              <!-- 选择框 -->
              <div class="select-box" @click.stop="toggleSelect(item, 'expired')">
                <el-icon v-if="isSelected(item, 'expired')"><Check /></el-icon>
                </div>
              
              <div class="card-header">
                <div class="card-title">
                  {{ item.name }}
                  <span class="expired-tag" v-if="item.expiryDate && calculateDaysRemaining(item.expiryDate) <= 0">已过期</span>
                </div>
                <div class="card-quantity">
                  <span class="quantity-label">数量:</span>
                  <span class="quantity-value low">{{ item.quantity }}</span>
                </div>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ item.location }}</span>
                </div>
                <div class="info-item">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>{{ getCategoryName(item.categoryId) }}</span>
                </div>
              </div>
              <div class="card-footer">
                <div class="card-date error">已过期: {{ item.expiryDate }}</div>
                <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
              </div>
              
              <!-- 添加操作按钮组 -->
              <div class="card-actions">
                <el-button type="danger" size="small" circle @click.stop="removeExpiredItem(item)">
                  <el-icon><Delete /></el-icon>
                </el-button>
                <el-button type="warning" size="small" circle @click.stop="decreaseQuantity(item)">
                  <el-icon><Minus /></el-icon>
                </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
      <!-- 数量充足物品 -->
      <div v-else-if="activeTab === 'sufficient'" class="inventory-list">
        <div v-if="filteredSufficientItems.length === 0" class="empty-state">
          <div class="empty-icon">📊</div>
          <h3>没有状态良好物品</h3>
          <p>当前没有数量充足且不即将过期的物品</p>
        </div>
        <div v-else>
          <div class="item-cards">
            <div 
              v-for="item in filteredSufficientItems" 
              :key="item.id"
              class="item-card sufficient"
              :class="{ 'selected': isSelected(item, 'sufficient') }"
              @click="showItemDetails(item)"
            >
              <!-- 选择框 -->
              <div class="select-box" @click.stop="toggleSelect(item, 'sufficient')">
                <el-icon v-if="isSelected(item, 'sufficient')"><Check /></el-icon>
              </div>
              
              <div class="card-header">
                <div class="card-title">
                  {{ item.name }}
                  <span class="good-status-tag" v-if="item.quantity > 3 && (!item.expiryDate || !calculateDaysRemaining(item.expiryDate) || calculateDaysRemaining(item.expiryDate) > 30)">状态良好</span>
                </div>
                <div class="card-quantity">
                <span class="quantity-label">数量:</span>
                  <span class="quantity-value sufficient">{{ item.quantity }}</span>
                </div>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ item.location }}</span>
                </div>
                <div class="info-item">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>{{ getCategoryName(item.categoryId) }}</span>
                </div>
              </div>
              <div class="card-footer">
                <div class="card-date">购买于: {{ formatDate(item.purchaseDate) }}</div>
                <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
              </div>
              
              <!-- 添加操作按钮组 -->
              <div class="card-actions">
                <el-button type="primary" size="small" circle @click.stop="updateQuantity(item, item.quantity + 1)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button type="warning" size="small" circle @click.stop="decreaseQuantity(item)">
                  <el-icon><Minus /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 全部物品内容区域 -->
      <div v-else-if="activeTab === 'allInventory'" class="inventory-list">
        <div v-if="consumableItems.length === 0 && !loading" class="empty-state">
          <div class="empty-icon">📦</div>
          <h3>库存为空</h3>
          <p>您还没有添加任何消耗品</p>
        </div>
        <div v-else>
          <div class="item-cards">
            <div 
              v-for="item in consumableItems" 
              :key="item.id"
              class="item-card" 
              :class="{ 'selected': isSelected(item, 'allInventory') }"
              @click="showItemDetails(item)"
            >
              <!-- 选择框 -->
              <div class="select-box" @click.stop="toggleSelect(item, 'allInventory')">
                <el-icon v-if="isSelected(item, 'allInventory')"><Check /></el-icon>
              </div>
              
              <div class="card-header">
                <div class="card-title">{{ item.name }}</div>
                <div class="card-quantity">
                  <span class="quantity-label">数量:</span>
                  <span class="quantity-value">{{ item.quantity }}</span>
                </div>
              </div>
              <div class="card-info">
                <div class="info-item">
                  <el-icon><OfficeBuilding /></el-icon>
                  <span>{{ item.locationName || item.location || '-' }}</span>
                </div>
                <div class="info-item">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>{{ item.categoryName || getCategoryName(item.categoryId) || '未知分类' }}</span>
                </div>
              </div>
              <div class="card-footer">
                <div class="card-date">
                  {{ item.expiryDate ? '过期日期: ' + formatDate(item.expiryDate) : '购买于: ' + formatDate(item.purchaseDate) }}
                </div>
                <div class="card-notes" :class="{'empty-notes': !item.notes}">{{ item.notes || '无备注' }}</div>
              </div>
              
              <!-- 操作按钮组 -->
              <div class="card-actions">
                <el-button type="primary" size="small" circle @click.stop="updateQuantity(item, item.quantity + 1)">
                  <el-icon><Plus /></el-icon>
                </el-button>
                <el-button type="warning" size="small" circle @click.stop="decreaseQuantity(item)">
                  <el-icon><Minus /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 物品详情编辑模态框 -->
    <ItemDetailModal
      v-model:visible="detailModalVisible"
      :item="itemToEdit"
      :categories="itemsStore.categories"
      :locations="itemsStore.locations"
      :statuses="itemsStore.statuses"
      :icons="icons"
      @save="handleDetailSave"
      @refresh="refreshItemData"
      @open-icon-selector="openIconSelector" 
    />

  </div>
</template>

<style scoped>
.inventory-view {
    position: relative;
    height: 100%;
    display: flex;
    flex-direction: column;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

.inventory-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0rem 0 0.5rem 4px;
}

.page-title {
    font-size: 1.75rem;
  font-weight: 600;
    color: #1d1d1f;
    margin: 0;
}

.inventory-tabs {
  display: flex;
    padding: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.08);
    margin-bottom: 1rem;
}

.tab {
  display: flex;
  align-items: center;
    padding: 0.75rem 1.5rem;
    color: #86868b;
    border-bottom: 2px solid transparent;
    cursor: pointer;
    transition: all 0.2s ease;
    margin-right: 1rem;
}

.tab:first-child {
    margin-left: 4px;
}

.tab:hover {
    color: #1d1d1f;
}

.tab.active {
    color: #0071e3;
    border-bottom-color: #0071e3;
}

.tab el-icon {
    margin-right: 0.5rem;
}

.tab-badge {
    background-color: rgba(0, 113, 227, 0.1);
    color: #0071e3;
    font-size: 0.8rem;
    padding: 0.2rem 0.5rem;
    border-radius: 100px;
    margin-left: 0.75rem;
}

.inventory-content {
    flex: 1;
    padding: 0 0rem 2rem;
    overflow-y: auto;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
    height: 300px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border-radius: 50%;
    border: 3px solid rgba(0, 113, 227, 0.1);
    border-top-color: #0071e3;
  animation: spin 1s linear infinite;
    margin-bottom: 1rem;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
    height: 300px;
    color: #86868b;
    text-align: center;
}

.empty-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.empty-state h3 {
    font-size: 1.2rem;
    font-weight: 500;
    margin: 0 0 0.5rem;
    color: #1d1d1f;
}

.item-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 0.8rem;
    margin-top: 0.75rem;
}

.item-card {
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
    padding: 0.6rem;
    transition: all 0.2s ease;
    cursor: default;
    border: 1px solid rgba(0, 0, 0, 0.05);
    position: relative;
    display: flex;
    flex-direction: column;
}

.item-card:hover {
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.item-card.expiring {
    border-left: 4px solid #ff9500;
}

.item-card.expired {
    border-left: 4px solid #ff3b30;
}

.item-card.consumable {
  border-left: 4px solid #34c759; /* 绿色边框表示消耗品 */
}

.item-card.sufficient {
  border-left: 4px solid #34c759; /* 绿色边框表示数量充足 */
}

.item-card.low-stock {
  border-left: 4px solid #ff9500; /* 黄色边框表示低库存 */
}

.quantity-value.sufficient {
  color: #34c759; /* 绿色文字表示数量充足 */
}

.quantity-value.low {
  color: #ff9500; /* 修改为黄色警告色 */
}

.card-header {
  display: flex;
    justify-content: space-between;
  align-items: center;
    margin-bottom: 0.5rem;
    margin-left: 12px;
}

.card-title {
    font-weight: 600;
    color: #1d1d1f;
    font-size: 1rem;
    cursor: pointer;
}

.card-quantity {
  display: flex;
    align-items: center;
    gap: 0.25rem;
}

.quantity-label {
    font-size: 0.85rem;
    color: #86868b;
}

.quantity-value {
    font-weight: 600;
    font-size: 0.9rem;
    color: #1d1d1f;
}

.card-info {
  display: flex;
  flex-direction: column;
    gap: 0.3rem;
    margin-bottom: 0.5rem;
    margin-left: 0;
}

.info-item {
  display: flex;
  align-items: center;
    color: #515154;
    font-size: 0.85rem;
}

.info-item el-icon {
    margin-right: 0.4rem;
    font-size: 1rem;
    color: #86868b;
}

.card-footer {
    margin-top: auto;
    padding-top: 0.5rem;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    font-size: 0.8rem;
    color: #86868b;
    margin-left: 0;
}

.card-date {
    margin-bottom: 0.2rem;
}

.warning {
    color: #ff9500;
}

.error {
    color: #ff3b30;
}

.card-notes {
    font-style: italic;
}

.card-notes.empty-notes {
    color: #c7c7cc;
    font-style: normal;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 6px;
  margin-top: 0.5rem;
  padding-top: 0.5rem;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  margin-left: 0;
}

/* 修改暗色模式下的边框颜色 */
.dark-mode .card-actions {
  border-top-color: rgba(255, 255, 255, 0.1);
}

.batch-actions {
    display: flex;
    align-items: center;
    gap: 10px;
}

.selected-count {
    font-size: 0.9rem;
    color: #86868b;
}

.select-all-container {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
}

.item-card.selected {
    border: 2px solid #0071e3;
    box-shadow: 0 4px 12px rgba(0, 113, 227, 0.15);
}

.select-box {
    position: absolute;
    top: 4px;
    left: 4px;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    border: 1px solid #d1d1d6;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    background-color: white;
    z-index: 2;
}

.select-box:hover {
    border-color: #0071e3;
}

.item-card.selected .select-box {
    border-color: #0071e3;
    background-color: #0071e3;
    color: white;
  }
  
.card-header {
    margin-left: 12px;
}

/* 为 header 中的按钮添加样式 */
.header-actions {
  margin-left: auto; /* 将按钮推到右边，靠近批量操作 */
  margin-right: 15px; /* 与批量操作保持间距 */
}

/* 统计弹窗样式 - 引用 StatisticsView.vue 的部分样式 */
:deep(.stats-detail-dialog) {
  border-radius: 12px; /* 圆角 */
}

:deep(.stats-detail-dialog .el-dialog__header) {
  padding: 16px 24px;
  border-bottom: 1px solid var(--el-border-color-lighter); /* 分隔线 */
  margin-right: 0; /* 覆盖默认 margin */
}

:deep(.stats-detail-dialog .el-dialog__title) {
  font-size: 1.1rem; /* 标题字号 */
  font-weight: 600;
  color: var(--el-text-color-primary);
}

:deep(.stats-detail-dialog .el-dialog__body) {
  padding: 30px 24px; /* 调整内边距 */
}

:deep(.stats-detail-dialog .el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid var(--el-border-color-lighter); /* 分隔线 */
}

.dialog-content {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 150px; /* 给加载区域一个最小高度 */
  text-align: center;
}

.loading-section {
  width: 100%; /* 让加载区域占满 */
  height: 100%;
}

/* 定制 el-loading 样式 */
:deep(.stats-detail-dialog .el-loading-mask) {
  display: flex;
  flex-direction: column; /* 图标在上，文字在下 */
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9); /* 轻微的背景遮罩 */
  border-radius: 12px; /* 确保遮罩也有圆角 */
}

:deep(.stats-detail-dialog .el-loading-spinner) {
  margin-top: 0; /* 移除默认顶部边距 */
  margin-bottom: 15px; /* 图标和文字之间的间距 */
}

/* 核心修改：调整加载图标样式 */
:deep(.stats-detail-dialog .el-loading-spinner .el-icon-loading) {
  font-size: 32px; /* 调整图标大小 */
  color: #409EFF; /* 设置为 Element Plus 的主蓝色 */
}

/* 如果需要更细的线条，可以尝试覆盖 SVG 属性，但这比较复杂且可能不稳定 */
/* 或者直接使用自定义的 SVG 或 CSS animation 来模拟 */

:deep(.stats-detail-dialog .el-loading-spinner .circular) {
  /* 移除之前的宽高设置，让字体大小控制 */
  /* width: 42px; */
  /* height: 42px; */
}

:deep(.stats-detail-dialog .el-loading-text) {
  color: #555; /* 加载文字颜色 */
  font-size: 14px;
  margin: 0;
}

.good-status-tag {
  display: inline-block;
  background-color: #34c759;
  color: white;
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 8px;
  margin-left: 8px;
}

.warning-tag {
  display: inline-block;
  background-color: #ff9500;
  color: white;
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 8px;
  margin-left: 8px;
}

.expired-tag {
  display: inline-block;
  background-color: #ff3b30;
  color: white;
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 8px;
  margin-left: 8px;
}

.expiring-tag {
  display: inline-block;
  background-color: #ff9500;
  color: white;
  font-size: 0.7rem;
  padding: 2px 6px;
  border-radius: 8px;
  margin-left: 8px;
}
</style> 